package xyz.thoughtset.viewer.modules.ds.jdbc.self.linker;


import lombok.SneakyThrows;
import xyz.thoughtset.viewer.common.connector.entity.bo.ConnectorMeta;
import xyz.thoughtset.viewer.common.connector.entity.bo.Linker;
import xyz.thoughtset.viewer.common.core.constants.FolderNameConstant;
import xyz.thoughtset.viewer.modules.ds.jdbc.core.linker.JdbcConnBuilder;

import java.io.File;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

//@Component
public class ManualConnBuilder extends JdbcConnBuilder {
    public ManualConnBuilder(Linker dataLinker) {
        super(dataLinker);
    }

    @SneakyThrows
    @Override
    public Object buildConnect(ConnectorMeta connectorMeta, Properties properties) {
        String appDir = System.getProperty("user.dir");

        // 构建相对路径指向 JDBC 驱动所在的目录
        String jarFilePath = FolderNameConstant.LINKER+File.separator+dataLinker.getJarFilePath();
//        File jarFile = new File(appDir, jdbcJarRelativePath);
        File file = new File(jarFilePath);
        if (!jarFilePath.startsWith("jar:file:")) {
            jarFilePath = "jar:file:" + jarFilePath;
        }
        if (!jarFilePath.endsWith("!/")) {
            jarFilePath = jarFilePath+"!/";
        }
        URL url = new URL("jar:file:" + file.getAbsolutePath() + "!/");
        JarURLConnection jarURLConnection = (JarURLConnection)url.openConnection();
//        URL[] urls = {jarFile.toURI().toURL()};
        JarFile jarFile = jarURLConnection.getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();

        URLClassLoader loader = new URLClassLoader(new URL[]{new URL(jarFilePath)}, ClassLoader.getSystemClassLoader());
        URLClassLoader classLoader = new URLClassLoader(new URL[] { url }, ClassLoader.getSystemClassLoader());
//        URLClassLoader classLoader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
        Thread.currentThread().setContextClassLoader(classLoader);
        if (!file.exists()) {
            throw new RuntimeException("JDBC JAR file not found at: " + file.getAbsolutePath());
        }
        return createDataSource(buildConfig(connectorMeta, properties));
    }
}
